<template>
  <view class="work-order-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无工单数据">
      <template #top>
        <!-- 保留navbar导航栏 -->
        <up-navbar title="工单管理" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>
      </template>

      <view class="content-wrapper">
        <!-- 汇总数据 -->
        <view class="summary-section">
          <view class="summary-header">
            <up-icon name="tags" size="24" color="#fff"></up-icon>
            <text class="summary-title">数据统计</text>
          </view>
          
          <!-- 工单统计网格布局 -->
          <view class="stats-grid">
            <view class="stats-item">
              <text class="stats-label">运维工单</text>
              <view class="stats-values">
                <view class="stats-value-container">
                  <text class="stats-value pending">{{ summaryData.maintenance.pending }}</text>
                  <text class="stats-label-small">待处理</text>
                </view>
                <view class="stats-value-container">
                  <text class="stats-value unassigned">{{ summaryData.maintenance.unassigned }}</text>
                  <text class="stats-label-small">未指派</text>
                </view>
              </view>
            </view>
            <view class="stats-item">
              <text class="stats-label">巡检工单</text>
              <view class="stats-values">
                <view class="stats-value-container">
                  <text class="stats-value pending">{{ summaryData.inspection.pending }}</text>
                  <text class="stats-label-small">待处理</text>
                </view>
                <view class="stats-value-container">
                  <text class="stats-value unassigned">{{ summaryData.inspection.unassigned }}</text>
                  <text class="stats-label-small">未指派</text>
                </view>
              </view>
            </view>
            <view class="stats-item">
              <text class="stats-label">退款工单</text>
              <view class="stats-values">
                <view class="stats-value-container">
                  <text class="stats-value pending">{{ summaryData.refund.pending }}</text>
                  <text class="stats-label-small">待处理</text>
                </view>
                <view class="stats-value-container">
                  <text class="stats-value unassigned">{{ summaryData.refund.unassigned }}</text>
                  <text class="stats-label-small">未指派</text>
                </view>
              </view>
            </view>
            <view class="stats-item">
              <text class="stats-label">异常工单</text>
              <view class="stats-values">
                <view class="stats-value-container">
                  <text class="stats-value pending">{{ summaryData.exception.pending }}</text>
                  <text class="stats-label-small">待处理</text>
                </view>
                <view class="stats-value-container">
                  <text class="stats-value unassigned">{{ summaryData.exception.unassigned }}</text>
                  <text class="stats-label-small">未指派</text>
                </view>
              </view>
            </view>
            <view class="stats-item">
              <text class="stats-label">故障工单</text>
              <view class="stats-values">
                <view class="stats-value-container">
                  <text class="stats-value pending">{{ summaryData.fault.pending }}</text>
                  <text class="stats-label-small">待处理</text>
                </view>
                <view class="stats-value-container">
                  <text class="stats-value unassigned">{{ summaryData.fault.unassigned }}</text>
                  <text class="stats-label-small">未指派</text>
                </view>
              </view>
            </view>
            <view class="stats-item">
              <text class="stats-label">指派任务</text>
              <view class="stats-values">
                <view class="stats-value-container">
                  <text class="stats-value pending">{{ summaryData.assignTask.pending }}</text>
                  <text class="stats-label-small">待处理</text>
                </view>
                <view class="stats-value-container">
                  <text class="stats-value unassigned">{{ summaryData.assignTask.unassigned }}</text>
                  <text class="stats-label-small">未指派</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 工单入口 -->
        <view class="entry-section">
          <text class="section-title">工单入口</text>
          <view class="entry-grid">
            <view class="entry-item" @click="navigateToWorkOrder('maintenance')">
              <image class="entry-icon" src="/static/images/maintenance-order.svg" mode="aspectFit"></image>
              <text class="entry-text">运维工单</text>
            </view>
            <view class="entry-item" @click="navigateToWorkOrder('inspection')">
              <image class="entry-icon" src="/static/images/inspection-order.svg" mode="aspectFit"></image>
              <text class="entry-text">巡检工单</text>
            </view>
            <view class="entry-item" @click="navigateToWorkOrder('refund')">
              <image class="entry-icon" src="/static/images/refund-order.svg" mode="aspectFit"></image>
              <text class="entry-text">退款工单</text>
            </view>
            <view class="entry-item" @click="navigateToWorkOrder('exception')">
              <image class="entry-icon" src="/static/images/exception-order.svg" mode="aspectFit"></image>
              <text class="entry-text">异常工单</text>
            </view>
            <view class="entry-item" @click="navigateToWorkOrder('fault')">
              <image class="entry-icon" src="/static/images/fault-order.svg" mode="aspectFit"></image>
              <text class="entry-text">故障工单</text>
            </view>
            <view class="entry-item" @click="navigateToWorkOrder('assignTask')">
              <image class="entry-icon" src="/static/images/assign-task.svg" mode="aspectFit"></image>
              <text class="entry-text">指派任务</text>
            </view>
          </view>
        </view>

        <!-- 快速操作 -->
        <!-- <view class="quick-actions">
          <text class="section-title">快速操作</text>
          <view class="action-grid">
            <view class="action-item" @click="createWorkOrder">
              <up-icon name="plus-circle" size="24" color="#007AFF"></up-icon>
              <text class="action-text">创建工单</text>
            </view>
            <view class="action-item" @click="batchAssign">
              <up-icon name="order" size="24" color="#FF9500"></up-icon>
              <text class="action-text">批量指派</text>
            </view>
            <view class="action-item" @click="viewStatistics">
              <up-icon name="file-text" size="24" color="#34C759"></up-icon>
              <text class="action-text">统计报表</text>
            </view>
            <view class="action-item" @click="exportData">
              <up-icon name="download" size="24" color="#5856D6"></up-icon>
              <text class="action-text">导出数据</text>
            </view>
          </view>
        </view> -->

        <!-- 工单列表 -->
        <view class="work-order-list">
          <text class="section-title">最近工单</text>
          <view class="list-container">
            <view v-for="(item, index) in currentList" :key="index" class="list-item">
              <view class="item-header">
                <view class="item-type" :class="item.type">
                  <text>{{ {
                    'maintenance': '运维',
                    'inspection': '巡检',
                    'refund': '退款',
                    'exception': '异常'
                  }[item.type] }}</text>
                </view>
                <view class="item-id">工单号: {{ item.id }}</view>
                <view class="item-status" :class="item.status">
                  <text>{{ {
                    'pending': '待处理',
                    'processing': '处理中',
                    'completed': '已完成',
                    'cancelled': '已取消'
                  }[item.status] }}</text>
                </view>
              </view>
              <view class="item-title">{{ item.title }}</view>
              <view class="item-info">
                <view class="info-row">
                  <text class="info-label">优先级:</text>
                  <text class="info-value priority" :class="item.priority">{{ {
                    'high': '高',
                    'medium': '中',
                    'low': '低'
                  }[item.priority] }}</text>
                </view>
                <view class="info-row">
                  <text class="info-label">负责人:</text>
                  <text class="info-value">{{ item.assignee || '未指派' }}</text>
                </view>
                <view class="info-row">
                  <text class="info-label">创建时间:</text>
                  <text class="info-value">{{ item.createTime }}</text>
                </view>
              </view>
              <view class="item-actions">
                <u-button type="primary" @click="viewWorkOrderDetail(item.id)">查看详情</u-button>
                <u-button type="primary" plain v-if="item.status === 'pending'"
                  @click="processWorkOrder(item.id)">处理工单</u-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getOperationCount } from '@/api';

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 汇总数据
const summaryData = ref({
  maintenance: {
    pending: 0,
    unassigned: 0
  },
  inspection: {
    pending: 0,
    unassigned: 0
  },
  refund: {
    pending: 0,
    unassigned: 0
  },
  exception: {
    pending: 0,
    unassigned: 0
  },
  fault: {
    pending: 0,
    unassigned: 0
  },
  abnormalBerth: {
    pending: 0,
    unassigned: 0
  },
  assignTask: {
    pending: 0,
    unassigned: 0
  }
});

// 获取工单数据汇总
const fetchOperationCount = async () => {
  try {
    const res = await getOperationCount();
    if (res.success) {
      const data = res.data;
      // 更新汇总数据
      summaryData.value = {
        maintenance: {
          pending: data.yw_gd_wait || 0,
          unassigned: data.yw_gd_ass || 0
        },
        inspection: {
          pending: data.xj_gd_wait || 0,
          unassigned: data.xj_gd_ass || 0
        },
        refund: {
          pending: data.tk_gd_wait || 0,
          unassigned: data.tk_gd_ass || 0
        },
        exception: {
          pending: data.err_gd_wait || 0,
          unassigned: data.err_gd_ass || 0
        },
        fault: {
          pending: data.gz_gd_wait || 0,
          unassigned: data.gz_gd_ass || 0
        },
        abnormalBerth: {
          pending: data.bw_gd_wait || 0,
          unassigned: data.bw_gd_ass || 0
        },
        assignTask: {
          pending: data.zp_gd_wait || 0,
          unassigned: data.zp_gd_ass || 0
        }
      };
      
      // 更新最近工单列表
      if (data.lately && data.lately.length > 0) {
        const records = data.lately.map(item => {
          // 转换工单类型
          const typeMap = {
            '22': 'maintenance', // 运维工单
            '23': 'inspection',  // 巡检工单
            '24': 'refund',      // 退款工单
            '25': 'exception',   // 异常工单
            '26': 'fault'        // 故障工单
          };
          
          // 转换状态
          const statusMap = {
            '0': 'pending',     // 待处理
            '1': 'processing',  // 已挂起（处理中）
            '2': 'completed',   // 已处理
            '3': 'cancelled'    // 已取消
          };
          
          // 转换优先级
          const levelMap = {
            '0': 'low',    // 低
            '1': 'medium', // 中
            '2': 'high'    // 高
          };
          
          return {
            id: item.id || item.bizCode,
            bizCode: item.bizCode,
            title: `${item.veName || ''}工单`,
            type: typeMap[item.type] || 'maintenance',
            status: statusMap[item.status] || 'pending',
            priority: levelMap[item.level] || 'medium',
            assignee: item.inspectorName || '',
            assigneeId: item.inspectorId || '',
            createTime: item.createTime || '',
            veName: item.veName || ''
          };
        });

        paging.value.complete(records);
      }
    } else {
      uni.showToast({
        title: res.msg || '获取数据失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取工单数据汇总失败:', error);
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    });
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

// 导航到工单页面
const navigateToWorkOrder = (type) => {
  const typeMap = {
    maintenance: '运维工单',
    inspection: '巡检工单',
    refund: '退款工单',
    exception: '异常工单',
    fault: '故障工单',
    abnormalBerth: '异常泊位',
    assignTask: '指派任务'
  };

  if (type === 'maintenance') {
    uni.navigateTo({
      url: '/pages/work-order/maintenance/index'
    });
  } else if (type === 'inspection') {
    uni.navigateTo({
      url: '/pages/work-order/inspection/index'
    });
  } else if (type === 'refund') {
    uni.navigateTo({
      url: '/pages/work-order/refund/index'
    });
  } else if (type === 'exception') {
    uni.navigateTo({
      url: '/pages/work-order/exception/index'
    });
  } else if (type === 'fault') {
    uni.navigateTo({
      url: '/pages/work-order/fault/index'
    });
  } else if (type === 'abnormalBerth') {
    uni.navigateTo({
      url: '/pages/work-order/abnormal-parking/index'
    });
  } else if (type === 'assignTask') {
    uni.navigateTo({
      url: '/pages/work-order/assign-task/index'
    });
  } else {
    uni.showToast({
      title: `跳转到${typeMap[type]}页面`,
      icon: 'none'
    });
    
    // 实际项目中应该跳转到对应的工单列表页面
    // uni.navigateTo({
    //   url: `/pages/work-order-list/index?type=${type}`
    // });
  }
};

// 创建工单
const createWorkOrder = () => {
  uni.showToast({
    title: '跳转到创建工单页面',
    icon: 'none'
  });

  // 实际项目中应该跳转到创建工单页面
  // uni.navigateTo({
  //   url: '/pages/work-order-create/index'
  // });
};

// 批量指派
const batchAssign = () => {
  uni.showToast({
    title: '跳转到批量指派页面',
    icon: 'none'
  });

  // 实际项目中应该跳转到批量指派页面
  // uni.navigateTo({
  //   url: '/pages/work-order-batch-assign/index'
  // });
};

// 查看统计
const viewStatistics = () => {
  uni.showToast({
    title: '跳转到统计报表页面',
    icon: 'none'
  });

  // 实际项目中应该跳转到统计报表页面
  // uni.navigateTo({
  //   url: '/pages/work-order-statistics/index'
  // });
};

// 导出数据
const exportData = () => {
  uni.showToast({
    title: '开始导出数据',
    icon: 'none'
  });

  // 实际项目中应该调用导出API
  // exportWorkOrderData();
};

// 查看工单详情
const viewWorkOrderDetail = (id) => {
  uni.showToast({
    title: `查看工单详情: ${id}`,
    icon: 'none'
  });

  // 实际项目中应该跳转到工单详情页面
  // uni.navigateTo({
  //   url: `/pages/work-order-detail/index?id=${id}`
  // });
};

// 处理工单
const processWorkOrder = (id) => {
  uni.showToast({
    title: `处理工单: ${id}`,
    icon: 'none'
  });

  // 实际项目中应该跳转到工单处理页面
  // uni.navigateTo({
  //   url: `/pages/work-order-process/index?id=${id}`
  // });
};

// 获取工单列表数据
const queryList = async (pageNo, pageSize) => {
  console.log('查询工单列表:', pageNo, pageSize);

  // 模拟API调用，实际项目中应该调用真实的API
  try {
    // 模拟数据
    const mockData = {
      records: [
        {
          id: '1001',
          type: 'maintenance',
          title: '设备维修工单',
          status: 'pending',
          createTime: '2023-05-15 10:30:00',
          assignee: '张工',
          priority: 'high'
        },
        {
          id: '1002',
          type: 'inspection',
          title: '设备巡检工单',
          status: 'processing',
          createTime: '2023-05-16 09:15:00',
          assignee: '李工',
          priority: 'medium'
        },
        {
          id: '1003',
          type: 'refund',
          title: '用户退款申请',
          status: 'pending',
          createTime: '2023-05-16 14:20:00',
          assignee: '',
          priority: 'high'
        },
        {
          id: '1004',
          type: 'exception',
          title: '系统异常报告',
          status: 'pending',
          createTime: '2023-05-17 08:45:00',
          assignee: '',
          priority: 'high'
        }
      ]
    };

    // 通知z-paging加载完成
    paging.value.complete(mockData.records || []);
  } catch (error) {
    console.error('获取工单列表失败:', error);
    paging.value.complete(false);
  }
};

// 页面挂载时获取汇总数据
onMounted(() => {
  // 获取工单数据汇总
  fetchOperationCount();
});
</script>

<style scoped lang="scss">
.work-order-page {
  padding: 20rpx;
}

.content-wrapper {
  padding: 20rpx;
}

.summary-section {
  background-color: #4a90e2;
  border-radius: 12rpx;
  margin: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  color: white;
}

.summary-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.summary-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
  margin-left: 15rpx;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15rpx;
  }

  .stats-item {
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 12rpx;
    padding: 12rpx 10rpx;
    display: flex;
    flex-direction: column;
  }

.stats-label {
  font-size: 26rpx;
  color: #fff;
  margin-bottom: 10rpx;
  text-align: center;
}

.stats-values {
  display: flex;
  justify-content: space-around;
}

.stats-value {
    font-size: 32rpx;
    font-weight: bold;
    line-height: 1.2;
  }

  .stats-value.pending {
    color: #FFEDA0;
  }
  
  .stats-value.unassigned {
    color: #FFADB3;
  }
  
  .stats-value-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 6rpx;
    min-width: 60rpx;
  }
  
  .stats-label-small {
    font-size: 20rpx;
    color: rgba(255, 255, 255, 0.9);
    margin-top: 6rpx;
    background-color: rgba(255, 255, 255, 0.15);
    padding: 2rpx 8rpx;
    border-radius: 10rpx;
  }

/* 工单入口样式 */

.entry-section,
.quick-actions {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.entry-grid,
.action-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.entry-item,
.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;

  &:active {
    background: #e9ecef;
    border-color: #007AFF;
    transform: scale(0.98);
  }
}

.entry-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 16rpx;
}

.entry-text,
.action-text {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  text-align: center;
}

.action-item {
  .up-icon {
    margin-bottom: 16rpx;
  }
}

/* 工单列表样式 */
.work-order-list {
  margin-top: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.list-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.list-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;

  &:last-child {
    border-bottom: none;
  }
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.item-type {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  color: #fff;
  font-weight: 500;

  &.maintenance {
    background: linear-gradient(135deg, #FFA5A5 0%, #FFBB8E 100%);
  }

  &.inspection {
    background: linear-gradient(135deg, #8C9EFF 0%, #9D7FD1 100%);
  }

  &.refund {
    background: linear-gradient(135deg, #4CAF50 0%, #8BC34A 100%);
  }

  &.exception {
    background: linear-gradient(135deg, #FF5722 0%, #FF9800 100%);
  }
}

.item-id {
  font-size: 24rpx;
  color: #666;
}

.item-status {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;

  &.pending {
    background: rgba(255, 152, 0, 0.1);
    color: #FF9800;
  }

  &.processing {
    background: rgba(33, 150, 243, 0.1);
    color: #2196F3;
  }

  &.completed {
    background: rgba(76, 175, 80, 0.1);
    color: #4CAF50;
  }

  &.cancelled {
    background: rgba(158, 158, 158, 0.1);
    color: #9E9E9E;
  }
}

.item-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.item-info {
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
  font-size: 26rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  color: #666;
  margin-right: 10rpx;
  min-width: 120rpx;
}

.info-value {
  color: #333;
  flex: 1;

  &.priority {
    &.high {
      color: #F44336;
    }

    &.medium {
      color: #FF9800;
    }

    &.low {
      color: #4CAF50;
    }
  }
}

.item-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.action-btn {
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  border: none;

  &.detail-btn {
    background: #f0f0f0;
    color: #333;
  }

  &.process-btn {
    background: #007AFF;
    color: #fff;
  }
}
</style>